package com.study.example.gameserver.socket.domain;
import com.sparrow.socket.tcp.session.impl.GameSession;
import com.study.example.gameserver.module.player.entity.Player;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ArgBuilder {

    // 枚举表示每个参数绑定类型
    private enum ArgType { SESSION, PLAYER, MESSAGE }

    // 缓存每个 Method 对应的参数类型映射
    private final Map<Method, ArgType[]> methodArgTypeCache = new ConcurrentHashMap<>();
    /**
     * 高性能 buildArgs
     */
    public Object[] buildArgs(GameSession session, Method method, Object msgPacket) {
        // 从缓存获取参数类型映射
        ArgType[] argTypes = methodArgTypeCache.computeIfAbsent(method, this::analyzeArgTypes);
        // 构造参数数组
        Object[] args = new Object[argTypes.length];
        for (int i = 0; i < argTypes.length; i++) {
            switch (argTypes[i]) {
                case SESSION:
                    args[i] = session;
                    break;
                case PLAYER:
                    args[i] = session.getEntity();
                    break;
                case MESSAGE:
                    args[i] = msgPacket;
                    break;
                default:
                    throw new IllegalStateException("Unexpected ArgType: " + argTypes[i]);
            }
        }
        return args;
    }

    /**
     * 注册阶段分析方法参数
     */
    private ArgType[] analyzeArgTypes(Method method) {
        Class<?>[] types = method.getParameterTypes();
        ArgType[] argTypes = new ArgType[types.length];
        for (int i = 0; i < types.length; i++) {
            if (types[i] == GameSession.class) {
                argTypes[i] = ArgType.SESSION;
            }
            else if (types[i] == Player.class) {
                argTypes[i] = ArgType.PLAYER;
            }
            else {
                argTypes[i] = ArgType.MESSAGE;
            }
        }
        return argTypes;
    }
}

